/**
 * 登录
 * @author Qasim <15750783791@163.com>
 * @version 2016/9/5
 */

document.addEventListener('plusready' , ready ,  false);

var self = previous_window = '';
 
var auths = {};

function ready(){  
	
	self = plus.webview.currentWebview(); 
	
	var member = plus.storage.getItem('memberInfo'); 
	
//	previous_window = previous_window.self_window;
	
//	if(member && !previous_window) {openNewpage('index.html');}
	
	//获取服务通道
	plus.oauth.getServices(function(services){
		
		for(var i in services){
			
			var service=services[i];
			
			auths[service.id]=service;
			
		}
		
	},function(e){
		
		plus.nativeUI.alert("获取登录认证失败："+e.message,null,'提示');
		
	});

	
	//前往注册
	$('.register').on('click' , function (){ 
		plus.nativeUI.showWaiting('跳转中...');
		
		var register_window = plus.webview.create('register.html' , 'register' , {} , {self_window : self.id}); 
		register_window.addEventListener('loaded' , function(){
			register_window.show('slide-in-bottom');
			plus.nativeUI.closeWaiting();
		})
		
	})
	
	//忘记密码
	$('.forget_pwd').on('click' , function (){ 
		plus.nativeUI.showWaiting('跳转中...');
		var forget_pwd_window = plus.webview.create('login-wj.html' , 'login-wj' , {} , {self_window : self.id}); 
		forget_pwd_window.addEventListener('loaded' , function(){
			forget_pwd_window.show('slide-in-bottom');
			plus.nativeUI.closeWaiting();
		})
		
	})
	
	//登录
	$('.login').on('click' , function(){
		
		var phone = $('input[name=phone]').val() , pass = $('input[name=pass]').val();
		
		if(!p1.test(phone)){
			
			toast('手机号码格式有误'); return;
			
		}
		
		if(!pass.trim()){
			
			toast('密码码不能为空'); return;
			
		}
		
		plus.nativeUI.showWaiting('登录中...');
		
		$.ajax({
			
			url : apiRoot + '/Home/Member/login/' , 
			
			type : 'post' , 
			
			data : {
				
				phone : phone , 
				
				pass : pass
				
			} , 
			
			success : function(data){
				
				plus.nativeUI.closeWaiting();
				
				var res = eval('('+data+')')
				
				if(res){ 
					
					toast('登录成功');
					
					//保存用户数据
					plus.storage.setItem('memberInfo' , data + '')
					
					relogin(plus.webview.currentWebview().id);
//					openNewpage('index.html');
					
				}else{
					
					toast('登录失败,请检查用户名或密码');
					
				}
				
			} , 
			error : function(e){
				
				plus.nativeUI.closeWaiting();
				
				toast('连接超时 ，请检查网络');
				
			}
		})
	})
	
	
	//第三方登录
	$('.login-ico div').each(function(index){ 
		
		$(this).on('click' , function(){
			
			if(index == 0) oauthLogin('weixin');
			
			if(index == 1) oauthLogin('qq');
			
		})
		
	})
}
/**
 * 第三方登录
 * @param {String} type
 */
function oauthLogin(type){
	var auth = auths[type];
	if(auth){
		var w = plus.nativeUI.showWaiting('授权中...',{width:'80px',height:'80px',background:'rgba(0,0,0,0.3)'});
		document.addEventListener("pause",function(){
			setTimeout(function(){
				w && w.close(); w = null;
			},2000);  
		}, false );
		auth.login(function(){ 
			w && w.close(); w = null;
			toast("登录认证成功");
			auth.getUserInfo(function(){ 
		        switch(type){
			        case 'weixin' : 
				       avatar = auth.userInfo.headimgurl;//头像 
				       name = auth.userInfo.nickname;
				       openid = auth.authResult.openid;
				       gender = auth.userInfo.sex;
				       break;
			       	case 'qq' : 
				       avatar = auth.userInfo.figureurl_qq_2;//头像 
				       name = auth.userInfo.nickname;
				       openid = auth.authResult.openid;
				       gender = auth.userInfo.gender == '男' ? 1 : 0 ;
				       break;
		        }	
				plus.nativeUI.showWaiting("登陆中...");
				$.ajax({//将用户信息存入数据库
					type:"post", 
					url:apiRoot + '/Home/Member/authLogin/',
					data : {
						user : name,
						avatar : avatar,
						gender : gender,
						nickname : name,
						login_type : type,
						openid : openid
					},
				    success: function(data){
				    	
				    	plus.nativeUI.closeWaiting(); 
				    	 
				    	if(data){
				    		
				    		var result = $.parseJSON(data);
				    		
				    		if(!p1.test(result.user)){
				    			plus.nativeUI.showWaiting('跳转中...');
					    		var register_window = plus.webview.create('register.html' , 'register' , {} , {self_window : self.id , aid : result.aid}); 
								register_window.addEventListener('loaded' , function(){
									register_window.show('slide-in-bottom');
									plus.nativeUI.closeWaiting();
								})
								
				    		}else{
				    			
				    			toast('登录成功');
								
								
								//保存用户数据
								plus.storage.setItem('memberInfo' , data + '')
								relogin(plus.webview.currentWebview().id);
//								openNewpage('index.html');
				    			
				    		}
				    		
				    	}
				    	
				    },error:function(e){ 
				    	
				        plus.nativeUI.closeWaiting();
				        
				      	console.log(JSON.stringify(e))
				    }
				});
			},function(e){
				toast("获取用户信息失败！");
			});
		},function(e){
			w && w.close(); w = null;
			toast("抱歉，您的手机没有该应用");
		});
	}else{
		toast("无效的登录认证通道！");
	}
}




window.addEventListener('register' , function(data){ 
	
	$('input[name=phone]').val(data.detail.phone)
	
})

function relogin(_self) {
	var all = plus.webview.all();
	for(var i in all) {
		if(all[i].id !== plus.runtime.appid && all[i].id !== _self) {
			all[i].close();   
		}
		if(i == all.length - 1) {
			var nwaiting = plus.nativeUI.showWaiting();//显示原生等待框
			var webviewContent= plus.webview.create('./index.html','index.html');//后台创建webview并打开show.html
			webviewContent.addEventListener("loaded", function() { //注册新webview的载入完成事件
			        nwaiting.close(); //新webview的载入完毕后关闭等待框
			        webviewContent.show("slide-in-right",20); //把新webview窗体显示出来，显示动画效果为速度200毫秒的右侧移入动画
			        }, false);
		}
	}
}

